<template>
  <a-button type="primary" v-if="hasExportAuth() && exportConfig" preIcon="ant-design:export-outlined" @click="onExport()"> 导出</a-button>
  <a-upload
    name="file"
    :showUploadList="false"
    v-if="hasImportAuth() && importConfig && !importConfig.showModal"
    :customRequest="(file) => onImport(file)"
  >
    <a-button type="primary" preIcon="ant-design:import-outlined">导入</a-button>
  </a-upload>

  <a-button
    type="primary"
    preIcon="ant-design:import-outlined"
    v-if="hasImportAuth() && importConfig && importConfig.showModal"
    @click="handleOpenExcelImport"
  >
    导入
  </a-button>
  <ExcelImportModal 
    @register="registerModal" 
    :importRequest="(data) => onImport(data)" 
    :exportConfig="exportConfig" :importConfig="importConfig"
    :bizType="bizType"
    :acceptFileTypes="acceptFileTypes"
  />
</template>

<script lang="ts" setup name="ExcelButton">
  import { PropType } from "vue"
  import qs from "qs"
  import { usePermission } from "/@/hooks/web/usePermission"
  import { useMethods } from "/@/hooks/system/useMethods"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { useModal } from "/@/components/Modal"
  import ExcelImportModal from "./ExcelImportModal.vue"
  import { useGlobSetting } from "/@/hooks/setting"
  import { excelProps } from './props'

  const glob = useGlobSetting()
  const [registerModal, { openModal }] = useModal()
  
  const props = defineProps(excelProps)
  const { hasPermission } = usePermission()
  const { handleExportXlsx, handleImportXls } = useMethods()

  const $message = useMessage()
  
  async function onExport() {
    let { url, name, params } = props?.exportConfig ?? {}
    if (url) {
      let title = typeof name === "function" ? name() : name
      return handleExportXlsx(title as string, url, params)
    } else {
      $message.createMessage.warn("没有传递 exportConfig.url 参数")
      return Promise.reject()
    }
  }

  async function onImport({ file, importParams }) {
    let { url, success, fail } = props?.importConfig ?? {}
    if (url) {
      let requestUrl = url
      requestUrl = glob.domainUrl + glob.urlPrefix + requestUrl + (requestUrl.indexOf('?') == -1 ? '?' : '&') + qs.stringify(importParams)
      return handleImportXls(file, requestUrl, success, fail)
    } else {
      $message.createMessage.warn("没有传递 import.url 参数")
      return Promise.reject()
    }
  }

  function handleOpenExcelImport() {
    openModal(true, {
      ...props.importConfig,
    })
  }

  // 导入按钮权限
  function hasImportAuth() {
    let auth = props?.importConfig?.auth
    return auth && auth.length > 0 ? hasPermission(auth) : true
  }

  // 导出按钮权限
  function hasExportAuth() {
    let auth = props?.exportConfig?.auth
    return auth && auth.length > 0 ? hasPermission(auth) : true
  }
</script>

<style scoped lang="less"></style>
